package org.arch_learn.io.nio.bytebuffer;


import java.nio.ByteBuffer;

/**
 * 操作缓冲区的核心api
 */
public class ReadByteBufferDemo {

    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);

        byteBuffer.put("01234".getBytes());
        System.out.println("position=" + byteBuffer.position());
        System.out.println("limit=" + byteBuffer.limit());
        System.out.println("capacity=" + byteBuffer.capacity());
        System.out.println("remaining=" + byteBuffer.remaining());

        System.out.println("----------------------------");

        //切换读模式
        byteBuffer.flip();
        System.out.println("position=" + byteBuffer.position());
        System.out.println("limit=" + byteBuffer.limit());
        System.out.println("capacity=" + byteBuffer.capacity());
        System.out.println("remaining=" + byteBuffer.remaining());
        for (int i = 0; i < byteBuffer.limit(); i++) {
            System.out.println(byteBuffer.get());
        }

        //读取指定索引的字节
        System.out.println(byteBuffer.get(1));

        //读取多个字节
//        byteBuffer.position(0);
        byteBuffer.rewind();//rewind()等同于将position置为0
        byte[] bytes = new byte[4];
        byteBuffer.get(bytes);
        System.out.println("读取到多个字节值为：" + new String(bytes));
        System.out.println("position=" + byteBuffer.position());
        System.out.println("limit=" + byteBuffer.limit());
        System.out.println("capacity=" + byteBuffer.capacity());
        System.out.println("remaining=" + byteBuffer.remaining());


        System.out.println("----------------------------");

        //将整个缓冲区转换为字节数组返回
        byte[] array = byteBuffer.array();
        System.out.println(new String(array));


        System.out.println("----------------------------");

        //切换写模式
        byteBuffer.clear();
        byteBuffer.put("abc".getBytes());
        array = byteBuffer.array();
        System.out.println(new String(array));
    }
}
